package com.janlei.tdd.practise;


import com.janlei.tdd.practise.model.Product;
import lombok.Getter;
import lombok.Setter;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import static java.util.stream.Collectors.toMap;

/**
 * Application code currently has following rules:
 * <p>
 * <pre>Calculates total price and total loyalty points earned by the customer.
 * Products with product code starting with DIS_10 have a 10% discount applied.
 * Products with product code starting with DIS_15 have a 15% discount applied.
 * Loyalty points are earned more when the product is not under any offer.
 * Customer earns 1 point on every $5 purchase.
 * Customer earns 1 point on every $10 spent on a product with 10% discount.
 * Customer earns 1 point on every $15 spent on a product with 15% discount.
 * </pre>
 *
 * @author admin
 */

@Getter
@Setter
public class ShoppingCart {

    List<Product> productList;

    public BigDecimal pay() {

        Map<String, Product> collect = productList.stream()
                .collect(toMap(Product::prefix, product -> product));


        AtomicReference<BigDecimal> res = new AtomicReference<>(BigDecimal.valueOf(0));
        collect.forEach((key, value) -> {

            double total = productList.stream()
                    .parallel()
                    .mapToDouble(Product::getRebate)
                    .sum();

            res.updateAndGet(v ->v.add(BigDecimal.valueOf(total)));
        });


        return res.get();
    }
}
